#include "game_rnd_vector.h"
#include "rand.h"

#include "util/mmgr.h"		    // Needs to come in early
#include <cassert>

using namespace num;


void RndVector::InitArray(int VectorSize, int ValidElementsCount, std::vector<int>& VectorToInit)
{
	VectorToInit.clear();

	if (VectorSize < 1)
		return;

	assert(ValidElementsCount > 0);

	VectorToInit.resize((unsigned long)VectorSize);

	for (int i = 0; i < VectorSize; i++)
		VectorToInit.at((unsigned long)i) = i % ValidElementsCount;
};

void RndVector::ShuffleArray(std::vector<int>& VectorToShuffle, int StepsCount)
{
	int VectorSize = (int)VectorToShuffle.size();

	assert(VectorSize > 0);

	for (int i = 0; i < StepsCount; i++)
	{
		int Index1 = RAND32::Instance().RandInt(0, VectorSize-1);
		int Index2 = RAND32::Instance().RandInt(0, VectorSize-1);
		
		int TmpVal = VectorToShuffle.at((unsigned long)Index1);
		VectorToShuffle.at((unsigned long)Index1) = VectorToShuffle.at(Index2);
		VectorToShuffle.at((unsigned long)Index2) = TmpVal;
	}
};



void RndVector::GetPlacesAccordingToScores(const std::vector<int>& ScoresVector, std::vector<int>& PlacesVector)
{
	std::vector<int> MyScores = ScoresVector;

	if (MyScores.size() < 1)
	{
		PlacesVector.clear();
		return;
	}

	if (MyScores.size() == 1)
	{
		PlacesVector.resize(1);
		PlacesVector.at(0) = 0;
		return;
	}

	PlacesVector.resize(MyScores.size());

	int i;

	for (i = 0; i < (int)PlacesVector.size(); i++)
		PlacesVector.at(i) = i;

	//bubble sorting scores :)

	bool Changed = true;

	while(Changed == true)
	{
		Changed = false;

		for (i = 0; i < (int)PlacesVector.size() - 1; i++)
		{
			if (MyScores.at(i) < MyScores.at(i+1))
			{
				//making the swap!
				
				//scores
				int tmpScore = MyScores.at(i+1);
				MyScores.at(i+1) = MyScores.at(i);
				MyScores.at(i) = tmpScore;

				//places
				int tmpPlace = PlacesVector.at(i+1);
				PlacesVector.at(i+1) = PlacesVector.at(i);
				PlacesVector.at(i) = tmpPlace;

				//change happened!
				Changed = true;
			}
		}
	}
}



